package com.xqq.lottery.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.xqq.lottery.util.Util;

import android.util.Log;

public class SocketAdapter {
	
	public static final byte DELAY = 0;
	public static final byte KEEPALIVE = 1;
	public static final byte LINGER = 2;
	public static final byte RCVBUF = 3;
	public static final byte SNDBUF = 4;
	public static final byte READ_WRITE = 0;
	
	private static final String TAG = "SocketAdapter";
	
	private Socket socket;
	private boolean sendSwitch = true;
	
	public boolean isSendSwitch(){
		return sendSwitch;
	}
	
	public void setSendSwitch(boolean sendSwitch){
		this.sendSwitch = sendSwitch;
	}
	
	private SocketAdapter (String host,int port)throws  IOException{
		socket =new Socket(host,port);
		socket.setKeepAlive(true);
	}
	
	private static SocketAdapter socketAdapter;
	
	
	public static synchronized SocketAdapter getSocketAdapterInstance(String host,int port)throws IOException{
		if(socketAdapter == null){
			socketAdapter =new SocketAdapter(host, port);
			Log.i(TAG, "new socket");
		}
		return socketAdapter;
	}
	
	public static synchronized SocketAdapter getSocketAdapterInstance() {
		return socketAdapter;
	}
	
	public InputStream openInputStream() throws IOException{
		return socket.getInputStream();
	}
	
	public OutputStream openOutputStream() throws IOException{
		return socket.getOutputStream();
	}
	
	
	public void close(){
		try{
			Thread.sleep(100);
			socket.close();
			socketAdapter = null;
		}catch(Exception e){
			e.printStackTrace();
		}
		socket = null;
	}
	
	
	public void setSocketOption(byte option,int value) throws IOException{
		if(socket == null){
			throw new IOException("Socket not available");
		}
		switch(option){
		case DELAY:
			socket.setTcpNoDelay(value == 0);
			break;
		case KEEPALIVE:
			socket.setKeepAlive(value == 0);
			break;
		case LINGER:
			socket.setSoLinger(true, value);
			break;
		case RCVBUF:
			socket.setReceiveBufferSize(value);
			break;
		case SNDBUF:
			socket.setSendBufferSize(value);
			break;
		}
	}

}
